# -*- coding: utf-8 -*-
__author__ = 'gongqf'

from ctms import sa


class User(sa.Model):
    __tablename__ = 't_user'
    u_id = sa.Column(sa.Integer, primary_key=True)
    u_user = sa.Column(sa.String(64), unique=True, nullable=False)
    u_name = sa.Column(sa.String(32), nullable=False)
    u_pass = sa.Column(sa.String(32), nullable=False)
    u_email = sa.Column(sa.String(120), index=True, unique=True)
    u_lastlogin = sa.Column(sa.DateTime)
    u_active = sa.Column(sa.Boolean, default=1)
    u_auth = sa.Column(sa.Boolean, default=1)

    # role = sa.Column(sa.SmallInteger, default = ROLE_USER)
    # posts = sa.relationship('Post', backref = 'author', lazy = 'dynamic')
    # about_me = sa.Column(sa.String(140))
    # followed = sa.relationship('User',
    #     secondary = followers,
    #     primaryjoin = (followers.c.follower_id == id),
    #     secondaryjoin = (followers.c.followed_id == id),
    #     backref = sa.backref('followers', lazy = 'dynamic'),
    #     lazy = 'dynamic')

    # @staticmethod
    # def make_unique_nickname(nickname):
    #     if User.query.filter_by(nickname = nickname).first() == None:
    #         return nickname
    #     version = 2
    #     while True:
    #         new_nickname = nickname + str(version)
    #         if User.query.filter_by(nickname = new_nickname).first() == None:
    #             break
    #         version += 1
    #     return new_nickname

    def is_authenticated(self):
        return unicode(self.u_auth)

    def is_active(self):
        return unicode(self.u_active)

    def is_anonymous(self):
        return False

    def get_uid(self):
        return unicode(self.uid)

    # def avatar(self, size):
    #     return 'http://www.gravatar.com/avatar/' + md5(self.email).hexdigest() + '?d=mm&s=' + str(size)
    #
    # def follow(self, user):
    #     if not self.is_following(user):
    #         self.followed.append(user)
    #         return self
    #
    # def unfollow(self, user):
    #     if self.is_following(user):
    #         self.followed.remove(user)
    #         return self
    #
    # def is_following(self, user):
    #     return self.followed.filter(followers.c.followed_id == user.id).count() > 0
    #
    # def followed_posts(self):
    #     return Post.query.join(followers, (followers.c.followed_id == Post.user_id)).filter(followers.c.follower_id == self.id).order_by(Post.timestamp.desc())

    def __repr__(self):
        return '<User %r>' % self.u_user